package com.casic.worklog.shiro;

import com.casic.worklog.model.Employee;
import com.casic.worklog.service.EmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import javax.annotation.Resource;


public class UserRealm extends AuthorizingRealm {
    @Resource
    private EmployeeService employeeService;


    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // 获取用户名
        String username = (String) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 给该用户设置角色，角色信息存在 t_role 表中取
        //authorizationInfo.setRoles(employeeService.getRoles(username));
        // 给该用户设置权限，权限信息存在 t_permission 表中取
        //authorizationInfo.setStringPermissions(employeeService.getPermissions(username));
        return authorizationInfo;
    }


    /**
     * 用来验证当前登录的用户，获取认证信息。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        // 查询用户信息
        Employee emp = null;
        try {
            emp = this.employeeService.findByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(emp != null) {
            // 把当前用户存到 Session 中
            SecurityUtils.getSubject().getSession().setAttribute("user", emp);
            // 传入用户名和密码进行身份认证，并返回认证信息
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(emp.getUsername(), emp.getPassword(), getName());
            return authcInfo;
        } else {
            return null;
        }
    }
}

